// pages/cartshop/cartshop.js
const app = getApp();
app.func.page({

    /**
     * 页面的初始数据
     */
    data: {
        cartshoplist: '',
        allcount: 0,
        totalPrice: '0.00',//初始价格
        selectAll: true,//是否全选
        hasList: false,//当购物车为空的时候
        myinfo: '',//判断账号
        clesr: false//判断购物车还是结算页面

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      let windowHeight = wx.getSystemInfoSync().windowHeight;
      console.log(windowHeight)
      const query = wx.createSelectorQuery();
   query.select('#runsekg').boundingClientRect();


   query.exec((res) => {
 let menutop = res[0].bottom;
  console.log(res); 
 this.setData({
scrollHeight:windowHeight-menutop
  })
})
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.getfristlist();
        this.myinfos();

    },


    getfristlist: function () {
        app.func.getPromise('/cartv2')
            .then(([code, res]) => {
                console.log(res.data);
                if (res.data.length == 0) {
                    this.setData({
                        selectAll: false,
                        hasList: true
                    })
                } else {
                    let cart = res.data;
                    cart.forEach((value, index) => {
                        value['checked'] = false
                    })
                    console.log(cart);
                    let allcount = 0
                    this.setData({
                        cartshoplist: cart,
                        allcount: allcount,
                        hasList: false
                    })

                    this.getTotalPrice();
                    // this.selectAll();
                }

            })
    },


    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },


    getTotalPrice() {
        let carts = this.data.cartshoplist; // 获取购物车列表
        let total = 0;
        let allcount = 0
        for (let i = 0; i < carts.length; i++) { // 循环列表得到每个数据
            if (carts[i].checked) { // 判断选中才会计算价格
                total += carts[i].count * carts[i].price; // 所有价格加起来
                allcount += carts[i].count

            } else {
                this.data.selectAll = false;
                this.setData({
                    selectAll: false
                })
            }
        }
        this.setData({ // 最后赋值到data中渲染到页面
            carts: carts,
            totalPrice: total.toFixed(2),
            allcount: allcount

        });
    },


    selectList(e) {
        const index = e.currentTarget.dataset.index; // 获取data- 传进来的index
        let carts = this.data.cartshoplist; // 获取购物车列表
        const selected = carts[index].checked; // 获取当前商品的选中状态
        carts[index].checked = !selected; // 改变状态
        this.setData({
            cartshoplist: carts
        });
        this.getTotalPrice(); // 重新获取总价
    },


    // 增加数量
    addCount(e) {
        const index = e.currentTarget.dataset.index;
        let carts = this.data.cartshoplist;
        let num = carts[index].count;
        num = num + 1;
        carts[index].count = num;
        let allcount = this.data.allcount + 1
        let id = carts[index].id
        app.func.postPromise('/setcartnumv2/' + id, {
            count: num
        }).then(res => {

            console.log(res)
        })
        this.setData({
            cartshoplist: carts,
            allcount,
        });
        this.getTotalPrice();
    },


    //减少数量
    incCount: function (e) {
        var that = this
        const index = e.currentTarget.dataset.index;
        let carts = that.data.cartshoplist;
        let num = carts[index].count;
        let id = carts[index].id
        num = num - 1;
        let allcount = that.data.allcount - 1
        // 单个删除商品
        if (num == 0) {
            // wx.showModal({
            //     title: '提示',
            //     content: '确定删除商品吗？',
            //     success: function (res) {
            //         if (res.confirm) {
            //             app.func.getPromise('/delcartv2/' + id)
            //                 .then(([code, res]) => {
            //                     if (code == 200) {
            //                         let carts = that.data.cartshoplist;
            //                         carts.splice(index, 1);
            //                         that.setData({
            //                             cartshoplist: carts
            //                         });
            //                         if (!carts.length) {
            //                             that.setData({
            //                                 hasList: true,
            //                                 totalPrice: 0.00,
            //                                 allcount: 0,
            //                                 selectAll: false

            //                             });
            //                             that.getTotalPrice();
            //                         } else {
            //                             that.getTotalPrice();
            //                         }
            //                     }
            //                 })
            //         } else {
            //             console.log('用户点击取消')
            //         }

            //     }
            // })

            return
        }
        app.func.postPromise('/setcartnumv2/' + id, {
            count: num
        }).then(res => {
            console.log(res)
        })
        carts[index].count = num;
        this.setData({
            cartshoplist: carts,
            allcount,
        });
        this.getTotalPrice();
    },
    // 全选事件
    selectAll(e) {
        let selectAll = this.data.selectAll; // 是否全选状态
        selectAll = !selectAll;
        let carts = this.data.cartshoplist || [];
        for (let i = 0; i < carts.length; i++) {
            carts[i].checked = selectAll; // 改变所有商品状态

        }

        // const selectAll = carts.length?carts.every(v=>v.checked):false;
        this.setData({
            selectAll: selectAll,
            cartshoplist: carts
        });
        this.getTotalPrice(); // 重新获取总价
    },
    //产品多选删除
    clearncart: function () {
        let that = this
        let carts = that.data.cartshoplist;
        var nwecarts = []
        carts.forEach(v => {
            console.log(v)
       if(v.checked){
        nwecarts.push(v.id);

       }
            
        })
        console.log(nwecarts);
        wx.showModal({
            title: '提示',
            content: '确定删除商品吗？',
            success: function (res) {
                if (res.confirm) {
                    app.func.postPromise('/batchdelchoosev2', {
                        pro_id: nwecarts
                    })
                        .then(([code, res]) => {
                            if (code == 200) {
                                // let carts = that.data.cartshoplist;
                                // carts.splice(0, carts.length);
                                that.onShow()
                                that.setData({
                                    // hasList: true,
                                    // totalPrice: 0.00,
                                    // allcount: 0,
                                    // selectAll: false,
                                    // cartshoplist: carts,
                                     clesr: false
                                });
                            }
                        })
                } else {
                    console.log('用户点击取消')
                }

            }
        })


    },
    myinfos() {
        app.func.getPromise('/my/info')
            .then(([code, res]) => {
                console.log(res.message)
                this.setData({
                    myinfo: res.message
                });
            })
    },
//结算按钮
    endplay: function () {
        let allcount = this.data.allcount;
        if (allcount == 0) {
            wx.showToast({
                title: '您还没有挑选商品',
                icon: 'none',
                mask: true
            })
            return;
        } else {
            //把商品用本地缓存存到缓存中
            let carts = this.data.cartshoplist;
            //用过滤器把商品的选中状态为true
            carts = carts.filter(v => v.checked)
                .map(function (c) {
                    return {id:c.id, count:c.count};
                })

            this.navigateModal('/pages/cartshop/payif/payif', {
                carts: carts
            });
        }
    },
//管理按钮
    setter: function () {
        this.setData({
            clesr: true
        })
    },
//取消管理按钮
    nosettet: function () {
        this.setData({
            clesr: false
        })
    },
    lookshop:function(){
        let extConfig = wx.getExtConfigSync? wx.getExtConfigSync(): {} ;
        if(extConfig.category = null || extConfig.category == 0) {
            wx.navigateTo({
                url: '/pages/index/categorysku/categorysku',
            })
        } else {
            wx.navigateTo({
                url: '/pages/index/newcategory/newcategory',
            })
        }
    },
    //单个商品删除
    deleti :function (e){
        var that = this
        const id= e.currentTarget.dataset.id;
        let index =e.currentTarget.dataset.index;
       wx.showModal({
                title: '提示',
                content: '确定删除商品吗？',
                success: function (res) {
                    if (res.confirm) {
                        app.func.getPromise('/delcartv2/' + id)
                            .then(([code, res]) => {
                                if (code == 200) {
                                    let carts = that.data.cartshoplist;
                                    carts.splice(index, 1);
                                    that.setData({
                                        cartshoplist: carts
                                    });
                                    if (!carts.length) {
                                        that.setData({
                                            hasList: true,
                                            totalPrice: 0.00,
                                            allcount: 0,
                                            selectAll: false

                                        });
                                        that.getTotalPrice();
                                    } else {
                                        that.getTotalPrice();
                                    }
                                }
                            })
                    } else {
                        console.log('用户点击取消')
                    }

                }
            })
    },
   
   
})
